import axios from 'axios'
import { Message, Loading } from 'element-ui'
import store from '@/store'
// import router from '../router'
// const configBaseUrl = 'http://localhost:8000/'
let loadingInstance = null
const notLoadingUrls = ['api/v1/open/type/query']
export const Service = axios.create({
  // baseURL: configBaseUrl,
  method: 'post',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

// 拦截器

Service.interceptors.request.use(
  (config) => {
    // 获取token,添加到请求头上
    const token = localStorage.getItem('loginToken') || ''
    if (token) {
      config.headers.common.Authorization = 'Bearer ' + token
    }
    let loadingFlag = true
    for (const url of notLoadingUrls) {
      if (config.url.includes(url)) {
        loadingFlag = false
      }
    }
    // 登录接口特殊处理
    if (config.url.includes('oauth/token')) {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    }
    if (loadingFlag) {
      loadingInstance = Loading.service({
        lock: true,
        text: 'loading...'
      })
    }
    return config
  },
  (error) => console.log(error)
)

Service.interceptors.response.use(
  (response) => {
    loadingInstance.close()
    return response.data
  },
  (error) => {
    const code = error.response ? error.response.status : 0
    switch (code) {
      case 401:
        store.dispatch('home/resetStatus')
        store.commit('login/setLoginStatus', { access_token: '' })
        // 登录页过期，给出错误提示
        if (error.response.config.url.includes('oauth/token')) {
          store.commit('login/setErrorMsg', { errMsg: error.response.data.msg })
        }
        // 首页如果出现401过期，则再次发起请求
        if (error.response.config.url.includes('api/v1/open/app/list')) {
          store.dispatch('home/getList').then()
        }
        // Message({
        //   message: error.response.data.msg,
        //   type: 'error',
        //   duration: 3000
        // })
        // setTimeout(() => {
        //   router.push({ path: '/login' })
        // }, 2000)
        break
      default:
        Message({
          message: error.response.data.msg,
          type: 'error',
          duration: 3000
        })
        break
    }
    loadingInstance.close()
    return Promise.reject(error)
  }
)
